<template>
  <div class="app-container">
    <el-row>
<!--      海报列表-->
      <el-col :span="5" :xs="24">
<!--        <div class="head-container">-->
<!--          <el-input-->
<!--            v-model="deptName"-->
<!--            placeholder="请输入部门名称"-->
<!--            clearable-->
<!--            size="small"-->
<!--            prefix-icon="el-icon-search"-->
<!--            style="margin-bottom: 20px"-->
<!--          />-->
<!--        </div>-->
        <div class="head-container">
          <el-table v-loading="loading"
                    :data="posterList"
                    @current-change="selectGardenListByPosterId"
                    highlight-current-row>
            <el-table-column label="海报类型" align="center" prop="typeName" width="80px"/>
            <el-table-column label="海报标题" align="left" prop="title" />
          </el-table>
        </div>
      </el-col>
      <el-col :span="19" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="区域" prop="areaId" >
            <el-select v-model="queryParams.areaId" placeholder="请选择区域" style="width:150px">
              <el-option
                v-for="area in areaList"
                :key="area.areaId"
                :label="area.areaName"
                :value="area.areaId"
              ></el-option>
            </el-select>
          </el-form-item>
<!--          <el-form-item label="类型" prop="type">-->
<!--            <el-select v-model="queryParams.type" placeholder="请选择" style="width:150px" clearable>-->
<!--              <el-option-->
<!--                v-for="dict in dict.type.sys_learning_garden_type"-->
<!--                :key="dict.value"-->
<!--                :label="dict.label"-->
<!--                :value="dict.value"-->
<!--              ></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-form-item label="标题" prop="title" style="width:480px">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入标题"
              clearable
              style="width:350px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:garden:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:garden:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:garden:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:garden:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading"
                  :data="gardenList"
                  border
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="40" align="center" />
          <el-table-column label="排序" align="center" prop="sort" width="50"/>
          <el-table-column label="区域" align="center" prop="areaName" width="60"/>
          <el-table-column label="标题" align="center" prop="title" width="250px"/>
<!--          <el-table-column label="小标题" align="center" prop="subtitle" width="230px"/>-->
          <el-table-column label="视频封面" align="center" prop="coverUrl" width="100px">
            <template slot-scope="scope">
              <image-preview :src="scope.row.coverUrl" :width="50" :height="50"/>
            </template>
          </el-table-column>
<!--          <el-table-column label="类型" align="center" prop="typeName" />-->
          <el-table-column label="发布人" align="center" prop="authorName" width="80px"/>
          <el-table-column label="发布时间" align="center" prop="publisherDate" width="95px">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.publisherDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
<!--          <el-table-column label="视频时长" align="center" prop="duration" />-->
          <el-table-column label="浏览量" align="center" prop="views" width="60px"/>
          <el-table-column label="状态" align="center" prop="status" width="60px">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_general_status" :value="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:garden:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:garden:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改学习园地对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="880px" :close-on-click-modal="false" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="区域" prop="areaId">
                  <el-select v-model="form.areaId" placeholder="请选择区域">
                    <el-option
                      v-for="area in areaList"
                      :key="area.areaId"
                      :label="area.areaName"
                      :value="area.areaId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="海报" prop="areaId" :span="12">
                  <el-select v-model="form.posterId" placeholder="请选择海报" clearable>
                    <el-option
                      v-for="poster in posterList"
                      :key="poster.posterId"
                      :label="poster.title"
                      :value="poster.posterId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="状态" prop="status">
                  <el-select v-model="form.status" placeholder="请选择" clearable size="small">
                    <el-option
                      v-for="dict in dict.type.sys_general_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="排序" prop="sort">
                  <el-input-number v-model="form.sort" controls-position="right" :min="0" placeholder="请输入排序号，值越小越靠前"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入标题" />
            </el-form-item>
            <el-form-item label="摘要" prop="subtitle">
              <el-input v-model="form.subtitle" placeholder="请输入摘要" />
            </el-form-item>
            <el-form-item label="视频封面" prop="coverUrl">
              <image-upload v-model="form.coverUrl" :limit="1"/>
            </el-form-item>
            <!--   参考博文     https://blog.csdn.net/jerrica/article/details/80854506-->
            <el-form-item label="视频上传" prop="videoUrl">
              <!-- action必选参数, 上传的地址 -->
              <el-upload class="avatar-uploader el-upload--text"
                         :action="uploadVideoUrl"
                         :headers="headers"
                         :show-file-list="false"
                         :before-upload="beforeUploadVideo"
                         :on-success="handleVideoSuccess"
                         :on-error="handleUploadError"
                         :on-remove="handleRemove"
                         :on-progress="uploadVideoProcess">
                <video v-if="form.videoUrl !='' && videoFlag == false" :src="getVideoUrl()" class="avatar" width="320" height="180" controls="controls">您的浏览器不支持视频播放</video>
                <i v-else-if="form.videoUrl =='' && videoFlag == false" class="el-icon-plus avatar-uploader-icon"></i>
                <el-progress v-if="videoFlag == true" type="circle" :percentage="parseFloat(videoUploadPercent)" style="margin-top:30px;margin-left: 100px"></el-progress>
              </el-upload>
              <!-- 上传提示 -->
              <div class="el-upload__tip">
                请上传
                <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
                <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
                的文件
              </div>
            </el-form-item>
<!--            <el-form-item label="视频时长" prop="duration">-->
<!--              <el-input v-model="form.duration" placeholder="由上传视频计算，不可手动编辑" readOnly/>-->
<!--            </el-form-item>-->
            <el-row>
              <el-col :span="8">
                <el-form-item label="发布人" prop="author">
                  <el-input v-model="form.authorName" placeholder="请输入发布人" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发布时间" prop="publisherDate">
                  <el-date-picker clearable size="small"
                                  v-model="form.publisherDate"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  placeholder="选择发布时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import { listGarden, getGarden, delGarden, addGarden, updateGarden } from "@/api/system/garden";
  import { listArea } from "@/api/system/area";
  import { getToken } from "@/utils/auth";
  import { getUserProfile } from "@/api/system/user";
  import { listPoster, getPoster, delPoster, addPoster, updatePoster } from "@/api/system/poster";

  export default {
    name: "Garden",
    dicts: ['sys_general_status', 'sys_learning_garden_type'],
    props: {
      value: [String, Object, Array],
      // 图片数量限制
      limit: {
        type: Number,
        default: 1,
      },
      // 大小限制(MB)
      fileSize: {
        type: Number,
        default: 500,
      },
      // 文件类型, 例如['png', 'jpg', 'jpeg']
      fileType: {
        type: Array,
        default: () => ["mp4","mov","avi"],
      },
      // 是否显示提示
      isShowTip: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        videoFlag:false,
        videoUploadPercent:{
        type: Number,
        default: 0,
        },
        dialogImageUrl: "",
        dialogVisible: false,
        hideUpload: false,
        baseUrl: process.env.VUE_APP_BASE_API,
        uploadVideoUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        fileList: [],

        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 学习园地表格数据
        gardenList: [],
        //学习海报列表
        posterList: [],
        //当前用户信息
        user:{},
        // 弹出层标题
        title: "",
        //当前选中的海报id
        currentPosterId:"",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          areaId: null,
          title: null,
          subtitle: null,
          videoUrl:null,
          coverUrl: null,
          type: null,
          author: null,
          publisherDate: null,
          duration: null,
          views: null,
          status: null,
          posterId:null,
        },
        // 表单参数
        form: {},
        //区域列表
        areaList:[],
        // 表单校验
        rules: {
          areaId: [
            { required: true, message: "区域不能为空", trigger: "blur" }
          ],
          title: [
            { required: true, message: "标题不能为空", trigger: "blur" }
          ],
          coverUrl: [
            { required: true, message: "请上传视频封面", trigger: "blur" }
          ],
          videoUrl: [
            { required: true, message: "请上传视频", trigger: "blur" }
          ],
        }
      };
    },
    created() {
      this.getPosterList();
      this.getList();
      this.getAreaList();
      this.getUser();
    },
    methods: {
      // 是否显示提示
      showTip() {
        return this.isShowTip && (this.fileType || this.fileSize);
      },
      /** 查询学习园地列表 */
      getList() {
        this.loading = true;
        listGarden(this.queryParams).then(response => {
          this.gardenList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 查询区域列表 */
      getAreaList() {
        listArea().then(response => {
          this.areaList = response.rows;
        });
      },

      getUser() {
        getUserProfile().then(response => {
          this.user = response.data;
          console.log("this.user:" + JSON.stringify(this.user))
        });
      },
      /** 查询学习海报列表 */
      getPosterList() {
        this.loading = true;
        listPoster({"status":"1"}).then(response => {
          this.posterList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },

      selectGardenListByPosterId(row){
        this.queryParams.posterId = row.posterId;
        this.currentPosterId = row.posterId;
        this.getList();
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          learningGardenId: null,
          areaId: null,
          title: null,
          subtitle: null,
          videoUrl: null,
          coverUrl: null,
          type: null,
          author: null,
          authorName: null,
          publisherDate: null,
          duration: null,
          views: null,
          status: "0",
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null,
          posterId:null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.learningGardenId)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.form.author = this.user.userId;
        this.form.authorName = this.user.userName;
        this.form.publisherDate=this.getNowTime();
        this.form.posterId = this.currentPosterId;
        this.open = true;
        this.title = "添加学习园地";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const learningGardenId = row.learningGardenId || this.ids
        getGarden(learningGardenId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改学习园地";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.learningGardenId != null) {
              updateGarden(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addGarden(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const learningGardenIds = row.learningGardenId || this.ids;
        this.$modal.confirm('是否确认删除学习园地编号为"' + learningGardenIds + '"的数据项？').then(function() {
          return delGarden(learningGardenIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/garden/export', {
          ...this.queryParams
        }, `garden_${new Date().getTime()}.xlsx`)
      },

      //处理默认选中当前日期
      getNowTime() {
        var now = new Date();
        var year = now.getFullYear(); //得到年份
        var month = now.getMonth(); //得到月份
        var date = now.getDate(); //得到日期
        month = month + 1;
        month = month.toString().padStart(2, "0");
        date = date.toString().padStart(2, "0");
        var defaultDate = `${year}-${month}-${date}`;
        console.log(defaultDate)
        return defaultDate;
        this.$set(this.form, "stockDate", publisherDate);
      },

      getVideoUrl(){
        var url =  this.baseUrl + this.form.videoUrl;
        console.log("=============url:" + url);
        return url;
      },

      // 文件个数超出
      handleExceed() {
        this.$message.error(`上传文件数量不能超过 ${this.limit} 个!`);
      },

      // 对象转成指定字符串分隔
      listToString(list, separator) {
        let strs = "";
        separator = separator || ",";
        for (let i in list) {
          strs += list[i].url.replace(this.baseUrl, "") + separator;
        }
        return strs != '' ? strs.substr(0, strs.length - 1) : '';
      },



      beforeUploadVideo(file) {
        let isImg = false;
        if (this.fileType.length) {
          let fileExtension = "";
          if (file.name.lastIndexOf(".") > -1) {
            fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
          }
          isImg = this.fileType.some(type => {
            if (file.type.indexOf(type) > -1) return true;
            if (fileExtension && fileExtension.indexOf(type) > -1) return true;
            return false;
          });
        } else {
          isImg = file.type.indexOf("image") > -1;
        }

        if (!isImg) {
          this.$message.error(
            `文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`
          );
          return false;
        }
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$message.error(`上传视频文件大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
      },
      uploadVideoProcess(event, file, fileList){
        this.videoFlag = true;
        console.log("file:",JSON.stringify(file));
        this.videoUploadPercent = file.percentage.toFixed(0);
      },
      handleVideoSuccess(res, file) {
          return new Promise(async (resolve, reject) => {
            console.log("res:",JSON.stringify(res));
            this.videoFlag = false;
            this.videoUploadPercent = 0;
            if(res.code == 200){
              this.form.videoUrl = res.fileName;

              var durationStr = "";
              let duration = await this.getVideoDuration(res.url);
              console.log("duration：",duration)
              var hour = null;
              var minute = null;
              var second = null;
              hour = parseInt(duration / 3600,0);
              duration = duration % 3600;
              minute =  parseInt(duration / 60);
              second = parseInt(duration % 60);
              minute = minute>9?minute:"0"+minute;
              second = second>9?second:"0"+second;
              if (hour > 0){
                durationStr = hour + ":";
              }
              durationStr = durationStr + minute + ":" + second;
              console.log("durationStr：",durationStr)
              this.form.duration = durationStr;
              this.isDisabled = true
              this.loading = true
              resolve();

            } else {

              this.$message.error('视频上传失败，请重新上传！');
            }
          })
      },

      // 上传失败
      handleUploadError() {
        this.$message({
          type: "error",
          message: "上传失败",
        });
        this.loading.close();
      },

      // 删除图片
      handleRemove(file, fileList) {
        const findex = this.fileList.map(f => f.name).indexOf(file.name);
        if(findex > -1) {
          this.fileList.splice(findex, 1);
          this.$emit("input", this.listToString(this.fileList));
        }
        this.form.videoUrl = null;
      },

      // 获取视频时长 参考： https://blog.csdn.net/tmj1763548838/article/details/120331494?spm=1001.2101.3001.6650.3&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-3.pc_relevant_paycolumn_v3&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-3.pc_relevant_paycolumn_v3&utm_relevant_index=6&ndash;&gt;
      getVideoDuration(url) {
        return new Promise(function(resolve, reject) {
          //做一些异步操作
          var audioElement = new Audio(url);
          let duration = 0
          audioElement.addEventListener('loadedmetadata', function() {
            duration = audioElement.duration //时长为秒，小数，182.36
            resolve(duration)
          })
        })
      }

    },

    watch: {
      value: {
        handler(val) {
          if (val) {
            // 首先将值转为数组
            const list = Array.isArray(val) ? val : this.value.split(',');
            // 然后将数组转为对象数组
            this.fileList = list.map(item => {
              if (typeof item === "string") {
                if (item.indexOf(this.baseUrl) === -1) {
                  item = { name: this.baseUrl + item, url: this.baseUrl + item };
                } else {
                  item = { name: item, url: item };
                }
              }
              return item;
            });
          } else {
            this.fileList = [];
            return [];
          }
        },
        deep: true,
        immediate: true
      }
    }

  };
</script>

<style scoped lang="scss">
  // .el-upload--picture-card 控制加号部分
  ::v-deep.hide .el-upload--picture-card {
    display: none;
  }
  // 去掉动画效果
  ::v-deep .el-list-enter-active,
  ::v-deep .el-list-leave-active {
    transition: all 0s;
  }

  ::v-deep .el-list-enter, .el-list-leave-active {
    opacity: 0;
    transform: translateY(0);
  }
</style>
